package com.fjnldx.mes.service.productionPlanManagement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjnldx.mes.domain.domainReq.AddDailyPlanLtReq;
import com.fjnldx.mes.domain.domainReq.AddDailyPlanQfReq;
import com.fjnldx.mes.domain.domainReq.AddDailyPlanReq;
import com.fjnldx.mes.domain.domainReq.QueryDevSnAndStatusReq;
import com.fjnldx.mes.domain.domainRes.*;
import com.fjnldx.mes.domain.pojo.DevSnAndStatus;
import com.fjnldx.mes.domain.pojo.MesDinger;
import com.fjnldx.mes.domain.pojo.MesNewscjhPojo;
import com.fjnldx.mes.domain.pojo.Scheduling;
import com.fjnldx.mes.mapper.mes.MesDingErMapper;
import com.fjnldx.mes.mapper.productionPlanManagement.ProductionPlanManagementMapper;
import com.fjnldx.mes.mapper.scheduling.SchedulingMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ProductionPlanManagementService extends ServiceImpl<ProductionPlanManagementMapper, MesNewscjhPojo> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ProductionPlanManagementMapper productionPlanManagementMapper;
    @Resource
    SchedulingMapper schedulingMapper;
    @Resource
    MesDingErMapper mesDingErMapper;

    public Result queryPzInfo(String gongxu, String pz) {
        QueryWrapper<MesDinger> wrapper = new QueryWrapper<>();
        wrapper.eq("gongxu", gongxu);
        wrapper.eq("pz", pz);
        wrapper.last("limit 1");
        MesDinger mesDinger = mesDingErMapper.selectOne(wrapper);
        return Result.success(mesDinger);
    }

    public Result addDailyPlanLt(AddDailyPlanLtReq data) {
        String cj = data.getCj();
        String pz = data.getPz();
        LocalDateTime time = data.getTime();
        List<String> devSnArea = data.getDevSnArea();
        String org = data.getOrg();
        QueryWrapper<MesNewscjhPojo> wrapper = new QueryWrapper<>();
        wrapper.clear();
        wrapper.eq("gongxu", "络筒")
                .apply(String.format("DATEDIFF(time,'%s')=0", time))
                .eq("cj", cj)
                .eq("pz", pz);
        List<MesNewscjhPojo> flag = productionPlanManagementMapper.selectList(wrapper);
        if (flag.size() > 0) {
            return Result.error("【车间、品种已存在，请前往页面上编辑】");
        } else {
            QueryWrapper<MesDinger> dingerQueryWrapper = new QueryWrapper<>();
            dingerQueryWrapper.eq("gongxu", "络筒");
            dingerQueryWrapper.eq("pz", pz);
            dingerQueryWrapper.last("limit 1");
            MesDinger mesDinger = mesDingErMapper.selectOne(dingerQueryWrapper);
            MesNewscjhPojo pojo = new MesNewscjhPojo();
            pojo.setOrg(org);
            pojo.setCj(cj);
            pojo.setPz(pz);
            pojo.setDs(mesDinger.getDs());
            pojo.setDl(mesDinger.getDl());
            pojo.setXiaolv(mesDinger.getXiaolv());
            pojo.setCs(mesDinger.getCs());
            pojo.setZl(mesDinger.getZl());
            pojo.setTc(mesDinger.getTc());
            pojo.setJisuan(mesDinger.getJisuan());
            pojo.setTime(time);
            pojo.setGongxu("络筒");
            for (String devSn : devSnArea) {
                pojo.setDevSn(devSn);
                productionPlanManagementMapper.insert(pojo);
            }

        }
        return Result.success("新增成功");
    }

    public Result addDailyPlanQf(AddDailyPlanQfReq data) {
        String cj = data.getCj();
        String pz = data.getPz();
        String gongxu = data.getGongxu();
        LocalDateTime time = data.getTime();
        List<String> devSnArea = data.getDevSnArea();
        if ("粗纱".equals(gongxu)) {
            return Result.error("请在细纱日计划中编辑粗纱");
        }
        QueryWrapper<MesNewscjhPojo> wrapper = new QueryWrapper<>();
        wrapper.clear();
        wrapper.eq("gongxu", gongxu)
                .apply(String.format("DATEDIFF(time,'%s')=0", time))
                .eq("cj", cj)
                .eq("pz", pz);
        List<MesNewscjhPojo> flag = productionPlanManagementMapper.selectList(wrapper);
        if (flag.size() > 0) {
            return Result.error("【" + cj + gongxu + pz + "已存在，请前往页面上编辑】");
        } else {
            QueryWrapper<MesDinger> dingerQueryWrapper = new QueryWrapper<>();
            dingerQueryWrapper.eq("gongxu", gongxu);
            dingerQueryWrapper.eq("pz", pz);
            dingerQueryWrapper.last("limit 1");
            MesDinger mesDinger = mesDingErMapper.selectOne(dingerQueryWrapper);
            MesNewscjhPojo pojo = new MesNewscjhPojo();
            pojo.setOrg(data.getOrg());
            pojo.setCj(data.getCj());
            pojo.setPz(data.getPz());
            pojo.setDs(mesDinger.getDs());
            pojo.setDl(mesDinger.getDl());
            pojo.setXiaolv(mesDinger.getXiaolv());
            pojo.setCs(mesDinger.getCs());
            pojo.setZl(mesDinger.getZl());
            pojo.setTc(mesDinger.getTc());
            pojo.setJisuan(mesDinger.getJisuan());
            pojo.setTime(data.getTime());
            pojo.setGongxu(gongxu);
            // 【抓棉：1|2；开棉1，2|3，4；多仓1，2|3，4】
            ArrayList<String> devQh1 = new ArrayList<>();
            devQh1.add("1");
            devQh1.add("2");
            ArrayList<String> devQh2 = new ArrayList<>();
            devQh2.add("3");
            devQh2.add("4");
            if ("抓棉".equals(gongxu) || "开棉".equals(gongxu) || "多仓".equals(gongxu)) {
                if (("抓棉".equals(gongxu) && devSnArea.contains("1")) || ("开棉".equals(gongxu) &&!Collections.disjoint(devSnArea,devQh1)) || ("多仓".equals(gongxu) && !Collections.disjoint(devSnArea,devQh1))) {
                    pojo.setGongxu("抓棉");
                    pojo.setDevSn("1");
                    productionPlanManagementMapper.insert(pojo);
                    for (String devSn : devQh1) {
                        pojo.setGongxu("开棉");
                        pojo.setDevSn(devSn);
                        productionPlanManagementMapper.insert(pojo);
                        pojo.setGongxu("多仓");
                        pojo.setDevSn(devSn);
                        productionPlanManagementMapper.insert(pojo);
                    }
                }
                if (("抓棉".equals(gongxu) && devSnArea.contains("2")) || ("开棉".equals(gongxu) && !Collections.disjoint(devSnArea,devQh2)) || ("多仓".equals(gongxu) && !Collections.disjoint(devSnArea,devQh2))) {
                    pojo.setGongxu("抓棉");
                    pojo.setDevSn("2");
                    productionPlanManagementMapper.insert(pojo);
                    for (String devSn : devQh2) {
                        pojo.setGongxu("开棉");
                        pojo.setDevSn(devSn);
                        productionPlanManagementMapper.insert(pojo);
                        pojo.setGongxu("多仓");
                        pojo.setDevSn(devSn);
                        productionPlanManagementMapper.insert(pojo);
                    }
                }
            } else {
                for (String devSn : devSnArea) {
                    pojo.setDevSn(devSn);
                    productionPlanManagementMapper.insert(pojo);
                }
            }
        }
        return Result.success("新增成功");
    }

    public Result addDailyPlan(AddDailyPlanReq data) {
        QueryWrapper<MesNewscjhPojo> queryWrapper = new QueryWrapper<>();
        String org = data.getOrg();
        String pzCs = data.getPzCs();
        List<String> devSnAreaCs = data.getDevSnAreaCs();
        String chph = data.getChph();
        String cjLt = data.getCjLt();
        List<String> jakt = data.getJakt();
        List<String> ybkt = data.getYbkt();
        String qk = data.getQk();
        String gongxu = data.getGongxu();
        String cj = data.getCj();
        List<String> devSnArea = data.getDevSnArea();
        String lc = data.getLc();
        String pz = data.getPz();
        LocalDateTime time = data.getTime();
        queryWrapper.eq("lc", lc)
                .eq("cj", cj)
                .eq("pz", pz)
                .apply(String.format("DATEDIFF(time,'%s')=0", time));
        List<MesNewscjhPojo> judgeList = productionPlanManagementMapper.selectList(queryWrapper);
        if (judgeList.size() > 0) {
            return Result.error("【" + lc + cj + pz + "】已存在，请前往页面编辑");
        }
        queryWrapper.clear();
        queryWrapper.eq("gongxu", gongxu)
                .orderByDesc("id")
                .last("limit 1");
        MesNewscjhPojo iMes = productionPlanManagementMapper.selectOne(queryWrapper);
        iMes.setOrg(org);
        iMes.setCj(cj);
        iMes.setLc(lc);
        iMes.setPz(pz);
        iMes.setChph(chph);
        iMes.setCjLt(cjLt);
        iMes.setJakt(StringUtils.join(jakt, ","));
        iMes.setYbkt(StringUtils.join(ybkt, ","));
        iMes.setQk(qk);
        iMes.setTime(time);
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        iMes.setDevSnAreaQf(uuid);
        for (String devSn : devSnArea) {
            iMes.setDevSn(devSn);
            productionPlanManagementMapper.insert(iMes);
        }
        queryWrapper.clear();
        queryWrapper.eq("gongxu", "粗纱")
                .orderByDesc("id")
                .last("limit 1");
        MesNewscjhPojo iMesCs = productionPlanManagementMapper.selectOne(queryWrapper);
        iMesCs.setDevSnAreaQf(uuid);
        iMesCs.setPz(pzCs);
        iMesCs.setTime(time);
        for (String devSn : devSnAreaCs) {
            iMesCs.setDevSn(devSn);
            productionPlanManagementMapper.insert(iMesCs);
        }
        return Result.success("添加成功!");
    }

    // 查询络筒机台可用状态
    public Result queryDevSnAndStatusLt(DevSnAndStatus data) {
        String gongxu = data.getGongxu();
        Integer id = data.getId();
        LocalDate time = data.getTime();
        List<Map<String, Object>> res;
        if (id == null) {
            res = productionPlanManagementMapper.queryDevSnAndStatusLtWithoutId(time);
        } else {
            MesNewscjhPojo mesTem;
            // 根据id查询该系列-cj、lc、pzCs、pz、cjLt模板记录
            mesTem = productionPlanManagementMapper.selectById(id);
            if (mesTem == null) {
                return Result.error("id错误");
            }
            String cj = mesTem.getCj();
            String pz = mesTem.getPz();
            res = productionPlanManagementMapper.queryDevSnAndStatusLt(cj, pz, time);
        }
        return Result.success(res);
    }

    public Result queryDevSnAndStatus(DevSnAndStatus data) {
        String gongxu = data.getGongxu();
        Integer id = data.getId();
        LocalDate time = data.getTime();
        List<Map<String, Object>> res;
        MesNewscjhPojo mesTem;
        switch (gongxu) {
            case "细纱":
                if (id == null) {
                    res = productionPlanManagementMapper.queryDevSnAndStatusXsWithoutId(time);
                } else {
                    mesTem = productionPlanManagementMapper.selectById(id);
                    if (mesTem == null) {
                        return Result.error("id错误");
                    }
                    String devSnAreaQf = mesTem.getDevSnAreaQf();
                    res = productionPlanManagementMapper.queryDevSnAndStatusXs(devSnAreaQf, time);
                }
                break;
            case "粗纱":
                if (id == null) {
                    res = productionPlanManagementMapper.queryDevSnAndStatusCsWithoutId(time);
                } else {
                    mesTem = productionPlanManagementMapper.selectById(id);
                    if (mesTem == null) {
                        return Result.error("前纺不支持更新粗纱，请前往细纱模块更新粗纱机台");
                    }
                    String devSnAreaQf = mesTem.getDevSnAreaQf();
                    res = productionPlanManagementMapper.queryDevSnAndStatusCs(devSnAreaQf, time);
                }
                break;
            case "络筒":
                if (id == null) {
                    res = productionPlanManagementMapper.queryDevSnAndStatusLtWithoutId(time);
                } else {
                    mesTem = productionPlanManagementMapper.selectById(id);
                    if (mesTem == null) {
                        return Result.error("id错误");
                    }
                    String cj = mesTem.getCj();
                    String pz = mesTem.getPz();
                    res = productionPlanManagementMapper.queryDevSnAndStatusLt(cj, pz, time);
                }
                break;
            default:
                ArrayList<String> dicBhList = new ArrayList<>();
                switch (gongxu) {
                    case "并条":
                        dicBhList.add("devSn_bt");
                        break;
                    case "梳棉":
                        dicBhList.add("devSn_sm");
                        dicBhList.add("devSn_sma");
                        break;
                    case "开棉":
                        dicBhList.add("devSn_kmj");
                        break;
                    case "多仓":
                        dicBhList.add("devSn_dc");
                        break;
                    case "抓棉":
                        dicBhList.add("devSn_zmj");
                        break;
                    default:
                }
                if (id == null) {
                    res = productionPlanManagementMapper.queryDevSnAndStatusQfWithoutId(time, gongxu, dicBhList);
                } else {
                    // 根据id查询该系列-cj、lc、pzCs、pz、cjLt模板记录
                    mesTem = productionPlanManagementMapper.selectById(id);
                    if (mesTem == null) {
                        return Result.error("id错误");
                    }
                    String cj = mesTem.getCj();
                    String pz = mesTem.getPz();
                    res = productionPlanManagementMapper.queryDevSnAndStatusQf(time, gongxu, cj, pz, dicBhList);
                }
                break;
        }
        return Result.success(res);
    }

    public Result deleteDailyPlan(Integer id) {
        MesNewscjhPojo pojo = productionPlanManagementMapper.selectById(id);
        String gongxu = pojo.getGongxu();
        String cj = pojo.getCj();
        String pz = pojo.getPz();
        LocalDateTime time = pojo.getTime();
        QueryWrapper<MesNewscjhPojo> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
        if ("细纱".equals(gongxu)) {
            queryWrapper.clear();
            queryWrapper.eq("devSnAreaQf", pojo.getDevSnAreaQf())
                    .eq("gongxu", "细纱")
                    .apply(String.format("DATEDIFF(time,'%s')=0", time));
            wrapper.clear();
            wrapper.eq("current_gongxu", "细纱")
                    .eq("cj", cj)
                    .apply(String.format("DATEDIFF(start_time,'%s')=0", time));
            // 删除粗纱
            QueryWrapper<MesNewscjhPojo> mesWrapperCs = new QueryWrapper<>();
            QueryWrapper<Scheduling> scWrapperCs = new QueryWrapper<>();
            mesWrapperCs.eq("devSnAreaQf", pojo.getDevSnAreaQf())
                    .eq("gongxu", "粗纱")
                    .apply(String.format("DATEDIFF(time,'%s')=0", time));
            scWrapperCs.eq("current_gongxu", "粗纱")
                    .eq("cj", cj)
                    .apply(String.format("DATEDIFF(start_time,'%s')=0", time));
            List<MesNewscjhPojo> devSnAreaList = productionPlanManagementMapper.selectList(mesWrapperCs);

            ArrayList<String> delAreaCs = new ArrayList<>();
            for (MesNewscjhPojo mesNewscjhPojo : devSnAreaList) {
                delAreaCs.add(mesNewscjhPojo.getDevSn());
            }
            if (delAreaCs.size() > 0) {
                scWrapperCs.in("devSn", delAreaCs);
                schedulingMapper.delete(scWrapperCs);
                mesWrapperCs.in("devSn", delAreaCs);
                productionPlanManagementMapper.delete(mesWrapperCs);
            }
        } else if ("络筒".equals(gongxu)) {
            queryWrapper.clear();
            queryWrapper.eq("cj", cj)
                    .eq("pz", pz)
                    .eq("gongxu", "络筒")
                    .apply(String.format("DATEDIFF(time,'%s')=0", time));
            wrapper.clear();
            wrapper.eq("cj", cj)
                    .eq("current_gongxu", "络筒")
                    .apply(String.format("DATEDIFF(start_time,'%s')=0", time));
        } else {
            queryWrapper.clear();
            queryWrapper.eq("cj", cj)
                    .eq("pz", pz)
                    .eq("gongxu", gongxu)
                    .apply(String.format("DATEDIFF(time,'%s')=0", time));
            wrapper.clear();
            wrapper.eq("cj", cj)
                    .eq("current_gongxu", gongxu)
                    .apply(String.format("DATEDIFF(start_time,'%s')=0", time));
        }
        ArrayList<String> delArea = new ArrayList<>();
        List<MesNewscjhPojo> devSnAreaList = productionPlanManagementMapper.selectList(queryWrapper);
        for (MesNewscjhPojo mesNewscjhPojo : devSnAreaList) {
            delArea.add(mesNewscjhPojo.getDevSn());
        }
        if (delArea.size() > 0) {
            wrapper.in("devSn", delArea);
            schedulingMapper.delete(wrapper);
            queryWrapper.in("devSn", delArea);
            productionPlanManagementMapper.delete(queryWrapper);
        }
        return Result.success("删除成功!");
    }

    public Result queryDailyPlan(QueryDevSnAndStatusReq queryDailyPlanXsReq) {
        String gongxu = queryDailyPlanXsReq.getGongxu();
        List<Map<String, Object>> queryDailyPlanInfos = new ArrayList<>();
        List<Map<String, Object>> queryDailyPlanXsQcSum = new ArrayList<>();
        List<Map<String, Object>> queryDailyPlanSumInfoByCj = new ArrayList<>();
        switch (gongxu) {
            case "细纱":
                queryDailyPlanInfos = productionPlanManagementMapper.queryDailyPlanXsInfo(queryDailyPlanXsReq);
                queryDailyPlanInfos.forEach((v -> {
                    v.put("jakt", String.valueOf(v.get("jakt")).split(","));
                    v.put("ybkt", String.valueOf(v.get("ybkt")).split(","));
                }));
                queryDailyPlanSumInfoByCj = productionPlanManagementMapper.queryDailyPlanXsCjSum(queryDailyPlanXsReq);
                queryDailyPlanXsQcSum = productionPlanManagementMapper.queryDailyPlanXsQcSum(queryDailyPlanXsReq);
                break;
            case "前纺":
                queryDailyPlanInfos = productionPlanManagementMapper.queryDailyPlanQfInfo(queryDailyPlanXsReq);
                queryDailyPlanSumInfoByCj = productionPlanManagementMapper.queryDailyPlanQfCjSum(queryDailyPlanXsReq);
                queryDailyPlanXsQcSum = productionPlanManagementMapper.queryDailyPlanQfQcSum(queryDailyPlanXsReq);
                break;
            case "络筒":
                queryDailyPlanInfos = productionPlanManagementMapper.queryDailyPlanLtInfo(queryDailyPlanXsReq);
                queryDailyPlanSumInfoByCj = productionPlanManagementMapper.queryDailyPlanLtCjSum(queryDailyPlanXsReq);
                queryDailyPlanXsQcSum = productionPlanManagementMapper.queryDailyPlanLtQcSum(queryDailyPlanXsReq);
                break;
            default:
                break;
        }
        for (Map<String, Object> data : queryDailyPlanInfos) {
            if ("细纱".equals(queryDailyPlanXsReq.getGongxu())) {
                String[] devSnAreaCs = String.valueOf(data.get("devSnAreaCs")).split(",");
                data.put("devSnAreaCs", devSnAreaCs);
            }
            String[] devSnArea = String.valueOf(data.get("devSnArea")).split(",");
            data.put("devSnArea", devSnArea);
        }

        String planner = productionPlanManagementMapper.queryDailyPlanXsOfPlanner(queryDailyPlanXsReq);

        QueryDailyPlanXsRes queryDailyPlanXsRes = new QueryDailyPlanXsRes();
        queryDailyPlanXsRes.setPlanInfo(queryDailyPlanInfos);
        queryDailyPlanXsRes.setCjSum(queryDailyPlanSumInfoByCj);
        queryDailyPlanXsRes.setQcSum(queryDailyPlanXsQcSum);
        queryDailyPlanXsRes.setPlanner(planner);
        return Result.success(queryDailyPlanXsRes);
    }

    public Result modifyDailyPlanLt(ModifyDailyPlanLtRes data) {
        QueryWrapper<Scheduling> schedulingQueryWrapper = new QueryWrapper<>();
        QueryWrapper<MesNewscjhPojo> mesWrapper = new QueryWrapper<>();
        QueryWrapper<MesDinger> mesDingErWrapper = new QueryWrapper<>();
        Integer id = data.getId();
        MesNewscjhPojo mesTem;
        if (id != null) {
            mesTem = productionPlanManagementMapper.selectById(id);
            if (mesTem == null) {
                return Result.error("id错误");
            }
        } else {
            return Result.error("id不能为空!");
        }
        LocalDateTime time = mesTem.getTime();
        String cj = mesTem.getCj();
        String pz = mesTem.getPz();
        logger.info("【业务开始】");
        List<String> devSnArea = data.getDevSnArea();
        if (devSnArea != null && devSnArea.size() > 0) {
            logger.info("【络筒机台范围修改】");
            // 存放新增机台
            ArrayList<String> addDevSnList = new ArrayList<>();
            // 存放删除机台
            ArrayList<String> delDevSnList = new ArrayList<>();
            // 旧机台范围
            ArrayList<String> devSnAreaOld = new ArrayList<>();
            mesWrapper.clear();
            mesWrapper.eq("gongxu", "络筒")
                    .apply(String.format("DATEDIFF(time,'%s')=0", time))
                    .eq("cj", cj)
                    .eq("pz", pz);
            List<MesNewscjhPojo> oldMes = productionPlanManagementMapper.selectList(mesWrapper);
            for (MesNewscjhPojo item : oldMes) {
                devSnAreaOld.add(item.getDevSn());
            }
            // 筛选新增机台
            for (String item : devSnArea) {
                if (!devSnAreaOld.contains(item) && !addDevSnList.contains(item)) {
                    addDevSnList.add(item);
                }
            }
            // 筛选删除机台
            for (String item : devSnAreaOld) {
                if (!devSnArea.contains(item)) {
                    delDevSnList.add(item);
                }
            }
            logger.info("存放新增机台---{}", addDevSnList.toString());
            logger.info("存放删除机台---{}", delDevSnList.toString());
            // 新增机台
            if (addDevSnList.size() > 0) {
                for (String devSn : addDevSnList) {
                    mesTem.setDevSn(devSn);
                    productionPlanManagementMapper.insert(mesTem);
                }
            }
            // 删除机台
            if (delDevSnList.size() > 0) {
                mesWrapper.in("devSn", delDevSnList);
                productionPlanManagementMapper.delete(mesWrapper);
                schedulingQueryWrapper.clear();
                schedulingQueryWrapper.eq("current_gongxu", "络筒")
                        .apply(String.format("DATEDIFF(start_time,'%s')=0", time))
                        .in("devSn", delDevSnList);
                schedulingMapper.delete(schedulingQueryWrapper);
            }

        } else {
            logger.info("【列数据修改】");
            String uCj = data.getCj();
            String uPz = data.getPz();
            String uLsjh = data.getLsjh();
            mesWrapper.clear();
            mesWrapper.eq("gongxu", "络筒")
                    .apply(String.format("DATEDIFF(time,'%s')=0", time))
                    .eq("cj", cj)
                    .eq("pz", pz);
            MesNewscjhPojo mesUpdate = new MesNewscjhPojo();
            if (!StringUtils.isEmpty(uPz)) {
                mesDingErWrapper.clear();
                mesDingErWrapper.eq("gongxu", "络筒");
                mesDingErWrapper.eq("pz", uPz);
                List<MesDinger> mesDingers = mesDingErMapper.selectList(mesDingErWrapper);
                if (mesDingers.size() > 0) {
                    MesDinger dinger = mesDingers.get(0);
                    mesUpdate.setPz(uPz);
                    mesUpdate.setDs(dinger.getDs());
                    mesUpdate.setDl(dinger.getDl());
                    mesUpdate.setXiaolv(dinger.getXiaolv());
                    mesUpdate.setCs(dinger.getCs());
                    mesUpdate.setZl(dinger.getZl());
                    mesUpdate.setTc(dinger.getTc());
                } else {
                    return Result.error("定额表中不存在该品种");
                }
            }
            if (!StringUtils.isEmpty(uCj)) {
                mesUpdate.setCj(cj);
            }
            if (!StringUtils.isEmpty(uLsjh)) {
                mesUpdate.setLsjh(uLsjh);
            }
            productionPlanManagementMapper.update(mesUpdate, mesWrapper);
        }
        return Result.success("修改成功");
    }

    public Result modifyDailyPlanQf(ModifyDailyPlanQfRes data) {
        QueryWrapper<Scheduling> schedulingQueryWrapper = new QueryWrapper<>();
        QueryWrapper<MesNewscjhPojo> mesWrapper = new QueryWrapper<>();
        QueryWrapper<MesDinger> mesDingErWrapper = new QueryWrapper<>();
        Integer id = data.getId();
        MesNewscjhPojo mesTem;
        if (id != null) {
            mesTem = productionPlanManagementMapper.selectById(id);
            if (mesTem == null) {
                return Result.error("id错误");
            }
        } else {
            return Result.error("id不能为空!");
        }
        LocalDateTime time = mesTem.getTime();
        String cj = mesTem.getCj();
        String pz = mesTem.getPz();
        String gongxu = mesTem.getGongxu();
        if ("粗纱".equals(gongxu)) {
            return Result.error("请在细纱日计划中编辑粗纱");
        }
        logger.info("【业务开始】");
        List<String> devSnArea = data.getDevSnArea();
        if (devSnArea != null && devSnArea.size() > 0) {
            logger.info("【前纺机台范围修改】");
            // 存放新增机台
            ArrayList<String> addDevSnList = new ArrayList<>();
            // 存放删除机台
            ArrayList<String> delDevSnList = new ArrayList<>();
            // 旧机台范围
            ArrayList<String> devSnAreaOld = new ArrayList<>();
            mesWrapper.clear();
            mesWrapper.eq("gongxu", gongxu)
                    .apply(String.format("DATEDIFF(time,'%s')=0", time))
                    .eq("cj", cj)
                    .eq("pz", pz);
            List<MesNewscjhPojo> oldMes = productionPlanManagementMapper.selectList(mesWrapper);
            for (MesNewscjhPojo item : oldMes) {
                devSnAreaOld.add(item.getDevSn());
            }
            // 筛选新增机台
            for (String item : devSnArea) {
                if (!devSnAreaOld.contains(item) && !addDevSnList.contains(item)) {
                    addDevSnList.add(item);
                }
            }
            // 筛选删除机台
            for (String item : devSnAreaOld) {
                if (!devSnArea.contains(item)) {
                    delDevSnList.add(item);
                }
            }
            logger.info("存放新增机台---{}", addDevSnList.toString());
            logger.info("存放删除机台---{}", delDevSnList.toString());
            // 新增机台
            if (addDevSnList.size() > 0) {
                for (String devSn : addDevSnList) {
                    mesTem.setDevSn(devSn);
                    productionPlanManagementMapper.insert(mesTem);
                }
            }
            // 删除机台
            if (delDevSnList.size() > 0) {
                mesWrapper.in("devSn", delDevSnList);
                productionPlanManagementMapper.delete(mesWrapper);
                schedulingQueryWrapper.clear();
                schedulingQueryWrapper.eq("current_gongxu", gongxu)
                        .apply(String.format("DATEDIFF(start_time,'%s')=0", time))
                        .in("devSn", delDevSnList);
                schedulingMapper.delete(schedulingQueryWrapper);
            }

        } else {
            logger.info("【列数据修改】");
            String uCj = data.getCj();
            String uPz = data.getPz();
            String uLsjh = data.getLsjh();
            String skjhqcd = data.getSkjhqcd();
            String xsjh = data.getXsjh();
            mesWrapper.clear();
            mesWrapper.eq("gongxu", gongxu)
                    .apply(String.format("DATEDIFF(time,'%s')=0", time))
                    .eq("cj", cj)
                    .eq("pz", pz);
            MesNewscjhPojo mesUpdate = new MesNewscjhPojo();
            if (!StringUtils.isEmpty(uPz)) {
                mesDingErWrapper.clear();
                mesDingErWrapper.eq("gongxu", gongxu);
                mesDingErWrapper.eq("pz", uPz);
                List<MesDinger> mesDingers = mesDingErMapper.selectList(mesDingErWrapper);
                if (mesDingers.size() > 0) {
                    MesDinger dinger = mesDingers.get(0);
                    mesUpdate.setPz(uPz);
                    mesUpdate.setDs(dinger.getDs());
                    mesUpdate.setDl(dinger.getDl());
                    mesUpdate.setXiaolv(dinger.getXiaolv());
                    mesUpdate.setCs(dinger.getCs());
                    mesUpdate.setZl(dinger.getZl());
                    mesUpdate.setTc(dinger.getTc());
                } else {
                    return Result.error("定额表中不存在该品种");
                }
            }
            if (!StringUtils.isEmpty(uCj)) {
                mesUpdate.setCj(cj);
            }
            if (!StringUtils.isEmpty(uLsjh)) {
                mesUpdate.setLsjh(uLsjh);
            }
            if (!StringUtils.isEmpty(skjhqcd)) {
                //mesUpdate.setJhcl(jhcl);
            }
            if (!StringUtils.isEmpty(xsjh)) {
                mesUpdate.setXsjh(xsjh);
            }
            productionPlanManagementMapper.update(mesUpdate, mesWrapper);
        }
        return Result.success("修改成功");
    }

    public Result modifyDailyPlan(ModifyDailyPlanRes data) {
        // 定位值：id
        // 修改值：车间、楼层、pzCs、devSnAreaCs、devSnArea、pz、lzPz、cjLt
        // devSnAreaQf:楼层、品种、车间唯一值
        //LocalDate time = data.getTime();
        //String org = data.getOrg();
        //String gongxu = data.getGongxu();
        QueryWrapper<Scheduling> schedulingQueryWrapper = new QueryWrapper<>();
        Integer id = data.getId();
        MesNewscjhPojo mesTem;
        if (id != null) {
            // 根据id查询该系列-cj、lc、pzCs、pz、cjLt模板记录
            mesTem = productionPlanManagementMapper.selectById(id);
            if (mesTem == null) {
                return Result.error("id错误");
            }
        } else {
            return Result.error("id不能为空!");
        }
        logger.info("【业务开始】");
        List<String> devSnArea = data.getDevSnArea();
        List<String> devSnAreaCs = data.getDevSnAreaCs();
        // 定位值
        LocalDateTime time = mesTem.getTime();
        String gongxu = mesTem.getGongxu();
        String devSnAreaQf = mesTem.getDevSnAreaQf();
        String cj = mesTem.getCj();
        String lc = mesTem.getLc();
        String pz = mesTem.getPz();
        QueryWrapper<MesNewscjhPojo> queryWrapper = new QueryWrapper<>();
        if (devSnArea != null && devSnArea.size() > 0) {
            logger.info("【细纱机台范围修改】");
            // 旧机台范围
            ArrayList<String> devSnAreaOld = new ArrayList<>();
            queryWrapper.clear();
            queryWrapper.eq("gongxu", gongxu)
                    .apply(String.format("DATEDIFF(time,'%s')=0", time))
                    .eq("devSnAreaQf", devSnAreaQf);
            List<MesNewscjhPojo> oldMes = productionPlanManagementMapper.selectList(queryWrapper);
            for (MesNewscjhPojo item : oldMes) {
                devSnAreaOld.add(item.getDevSn());
            }
            // 存放新增机台
            ArrayList<String> addDevSnList = new ArrayList<>();
            // 存放删除机台
            ArrayList<String> delDevSnList = new ArrayList<>();
            // 筛选新增机台
            for (String item : devSnArea) {
                if (!devSnAreaOld.contains(item) && !addDevSnList.contains(item)) {
                    addDevSnList.add(item);
                }
            }
            // 筛选删除机台
            for (String item : devSnAreaOld) {
                if (!devSnArea.contains(item)) {
                    delDevSnList.add(item);
                }
            }
            logger.info("存放新增机台---{}", addDevSnList.toString());
            logger.info("存放删除机台---{}", delDevSnList.toString());
            // 新增机台
            if (addDevSnList.size() > 0) {
                for (String devSn : addDevSnList) {
                    mesTem.setDevSn(devSn);
                    productionPlanManagementMapper.insert(mesTem);
                }
            }
            // 删除机台
            if (delDevSnList.size() > 0) {
                queryWrapper.in("devSn", delDevSnList);
                productionPlanManagementMapper.delete(queryWrapper);
                schedulingQueryWrapper.clear();
                schedulingQueryWrapper.eq("current_gongxu", gongxu)
                        .apply(String.format("DATEDIFF(start_time,'%s')=0", time))
                        .in("devSn", delDevSnList);
                schedulingMapper.delete(schedulingQueryWrapper);
            }
        } else if (devSnAreaCs != null && devSnAreaCs.size() > 0) {
            logger.info("【粗纱机台范围修改】");
            // 旧机台范围
            ArrayList<String> devSnAreaOldCs = new ArrayList<>();
            queryWrapper.clear();
            queryWrapper.eq("gongxu", "粗纱")
                    .apply(String.format("DATEDIFF(time,'%s')=0", time))
                    .eq("devSnAreaQf", devSnAreaQf);
            List<MesNewscjhPojo> oldMesCs = productionPlanManagementMapper.selectList(queryWrapper);
            MesNewscjhPojo mesCsTem = new MesNewscjhPojo();
            if (oldMesCs != null) {
                mesCsTem = oldMesCs.get(0);
                for (MesNewscjhPojo item : oldMesCs) {
                    devSnAreaOldCs.add(item.getDevSn());
                }
            } else {
                // 从0开始新增粗纱
                mesCsTem.setOrg(mesTem.getOrg());
                mesCsTem.setCj(mesTem.getCj());
                mesCsTem.setPz("RAA重-5");
                mesCsTem.setGongxu("粗纱");
                mesCsTem.setTime(mesTem.getTime());
                mesCsTem.setDs("132");
                mesCsTem.setDl("5.42");
                mesCsTem.setXiaolv("85");
                mesCsTem.setCs("23.9");
                mesCsTem.setTc("2093");
                mesCsTem.setJisuan("2093");
                mesCsTem.setLc(mesTem.getLc());
                mesCsTem.setDevSnAreaQf(mesTem.getDevSnAreaQf());
            }
            // 存放新增机台
            ArrayList<String> addDevSnListCs = new ArrayList<>();
            // 存放删除机台
            ArrayList<String> delDevSnListCs = new ArrayList<>();
            // 筛选新增机台
            for (String devSn : devSnAreaCs) {
                if (!devSnAreaOldCs.contains(devSn) && !addDevSnListCs.contains(devSn)) {
                    addDevSnListCs.add(devSn);
                }
            }
            // 筛选删除机台
            for (String devSn : devSnAreaOldCs) {
                if (!devSnAreaCs.contains(devSn)) {
                    delDevSnListCs.add(devSn);
                }
            }
            logger.info("存放新增机台---{}", addDevSnListCs.toString());
            logger.info("存放删除机台---{}", delDevSnListCs.toString());
            // 新增机台
            if (addDevSnListCs.size() > 0) {
                for (String devSn : addDevSnListCs) {
                    mesCsTem.setDevSn(devSn);
                    productionPlanManagementMapper.insert(mesCsTem);
                }
            }
            // 删除机台
            if (delDevSnListCs.size() > 0) {
                queryWrapper.in("devSn", delDevSnListCs);
                productionPlanManagementMapper.delete(queryWrapper);
                schedulingQueryWrapper.clear();
                schedulingQueryWrapper.eq("current_gongxu", "粗纱")
                        .apply(String.format("DATEDIFF(start_time,'%s')=0", time))
                        .in("devSn", delDevSnListCs);
                schedulingMapper.delete(schedulingQueryWrapper);
            }

        } else {
            logger.info("【列数据修改】（车间、楼层、前纺品种、品种、劳资品种、络筒车间,甲a开台，乙b开台）");
            // 修改值
            String uCj = data.getCj();
            String uLc = data.getLc();
            String uPz = data.getPz();
            String uCjLt = data.getCjLt();
            String chph = data.getChph();
            String uPzCs = data.getPzCs();
            List<String> jakt = data.getJakt();
            List<String> ybkt = data.getYbkt();
            if (jakt != null || ybkt != null || !StringUtils.isEmpty(chph) || !StringUtils.isEmpty(uCj) || !StringUtils.isEmpty(uLc) || !StringUtils.isEmpty(uPz) || !StringUtils.isEmpty(uLc)) {
                // 更新细纱日计划
                // 细纱日计划修改条件
                queryWrapper.clear();
                queryWrapper.eq("gongxu", gongxu)
                        .apply(String.format("DATEDIFF(time,'%s')=0", time))
                        .eq("devSnAreaQf", devSnAreaQf);
                MesNewscjhPojo mesUpdate = new MesNewscjhPojo();
                if (!StringUtils.isEmpty(uCj)) {
                    mesUpdate.setCj(uCj);
                }
                if (!StringUtils.isEmpty(uLc)) {
                    mesUpdate.setLc(uLc);
                }
                if (!StringUtils.isEmpty(uPz)) {
                    mesUpdate.setPz(uPz);
                }
                if (!StringUtils.isEmpty(uLc)) {
                    mesUpdate.setCjLt(uCjLt);
                }
                if (!StringUtils.isEmpty(chph)) {
                    mesUpdate.setChph(chph);
                }
                if (jakt != null) {
                    mesUpdate.setJakt(StringUtils.join(jakt, ","));
                }
                if (ybkt != null) {
                    mesUpdate.setYbkt(StringUtils.join(ybkt, ","));
                }
                productionPlanManagementMapper.update(mesUpdate, queryWrapper);
            }
            if (!StringUtils.isEmpty(uPzCs)) {
                queryWrapper.clear();
                queryWrapper.eq("gongxu", "粗纱")
                        .apply(String.format("DATEDIFF(time,'%s')=0", time))
                        .eq("devSnAreaQf", devSnAreaQf);
                MesNewscjhPojo mesUpdateCs = new MesNewscjhPojo();
                // 更新粗纱日计划
                mesUpdateCs.setPz(uPzCs);
                productionPlanManagementMapper.update(mesUpdateCs, queryWrapper);
            }
        }
        return Result.success("更新成功");
    }
}
